package io.youngking.modules.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import io.youngking.common.exception.RRException;
import io.youngking.common.utils.ImageHelper;
import io.youngking.common.utils.R;
import io.youngking.modules.article.entity.ArticleEntity;
import io.youngking.modules.article.service.ArticleService;
import io.youngking.modules.articlearea.entity.ArticleareaEntity;
import io.youngking.modules.articlearea.service.ArticleareaService;
import io.youngking.modules.articletype.entity.ArticletypeEntity;
import io.youngking.modules.articletype.service.ArticletypeService;
import io.youngking.modules.breakfast.entity.BreakfastEntity;
import io.youngking.modules.breakfast.service.BreakfastService;
import io.youngking.modules.feedback.entity.FeedbackEntity;
import io.youngking.modules.feedback.service.FeedbackService;
import io.youngking.modules.good.entity.GoodEntity;
import io.youngking.modules.good.service.GoodService;
import io.youngking.modules.goodnotice.entity.GoodnoticeEntity;
import io.youngking.modules.goodnotice.service.GoodnoticeService;
import io.youngking.modules.goodreceipt.entity.GoodreceiptEntity;
import io.youngking.modules.goodreceipt.service.GoodreceiptService;
import io.youngking.modules.goodrecepititem.entity.GoodrecepititemEntity;
import io.youngking.modules.goodrecepititem.service.GoodrecepititemService;
import io.youngking.modules.goodtype.entity.GoodtypeEntity;
import io.youngking.modules.goodtype.service.GoodtypeService;
import io.youngking.modules.hotelinfo.entity.HotelinfoEntity;
import io.youngking.modules.hotelinfo.service.HotelinfoService;
import io.youngking.modules.roominfo.entity.RoominfoEntity;
import io.youngking.modules.roominfo.service.RoominfoService;
import io.youngking.modules.roomreceipt.entity.RoomreceiptEntity;
import io.youngking.modules.roomreceipt.service.RoomreceiptService;
import io.youngking.modules.roomtype.entity.RoomtypeEntity;
import io.youngking.modules.roomtype.service.RoomtypeService;
import io.youngking.modules.roomuser.entity.RoomuserEntity;
import io.youngking.modules.roomuser.service.RoomuserService;
import io.youngking.modules.wxuserinfo.entity.WxuserinfoEntity;
import io.youngking.modules.wxuserinfo.service.WxuserinfoService;
import io.youngking.weixin4j.Weixin;
import io.youngking.weixin4j.model.message.template.TemplateData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import io.youngking.weixin4j.WeixinException;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.github.binarywang.wxpay.bean.request.BaseWxPayRequest.yuanToFen;
import static io.youngking.common.utils.Common.getRandomChar;
import static io.youngking.weixin4j.util.SignUtil.getSign;

/**
 * 公众号数据接口
 *
 * @author lifei
 */
@RestController
@RequestMapping("/app/weixinapp")
@PropertySource("classpath:weixin4j.properties")
public class WeixinAppCotroller {
    @Autowired
    private ArticleareaService articleareaService;
    @Autowired
    private ArticletypeService articletypeService;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private GoodtypeService goodtypeService;
    @Autowired
    private GoodService goodService;
    @Autowired
    private GoodreceiptService goodreceiptService;
    @Autowired
    private GoodrecepititemService goodrecepititemService;
    @Autowired
    private RoomuserService roomuserService;
    @Autowired
    private RoominfoService roominfoService;
    @Autowired
    private WxuserinfoService wxuserinfoService;
    @Autowired
    private HotelinfoService hotelinfoService;
    @Autowired
    private FeedbackService feedbackService;
    @Autowired
    private BreakfastService breakfastService;
    @Autowired
    private GoodnoticeService goodnoticeService;
    @Autowired
    private RoomreceiptService roomreceiptService;
    @Autowired
    private RoomtypeService roomtypeService;
    @Autowired
    private WxPayService wxService;

    @Value("${weixin4j.oauth.appid}")
    private String appId;  //公众号appid
    @Value("${weixin4j.pay.partner.id}")
    private String payId;  //商户支付id
    @Value("${weixin4j.pay.partner.key}")
    private String paySerect;  //商户支付秘钥

    /**
     * 文章攻略区域、类别
     *
     * @return
     */
    @RequestMapping("/articletype")
    public R gettype() {
        List<ArticleareaEntity> articleareaEntities = articleareaService.selectList(new EntityWrapper<ArticleareaEntity>().eq("isshow", 0).orderBy("sort desc,id desc"));
        List<ArticletypeEntity> articletypeEntities = articletypeService.selectList(new EntityWrapper<ArticletypeEntity>().eq("isshow", 0).orderBy("sort desc,id desc"));
        return R.ok().put("arealist", articleareaEntities).put("typelist", articletypeEntities);
    }

    /**
     * 文章攻略内容
     */
    @RequestMapping("/articlelist")
    public R getarticle(@RequestBody String simpleObject) {
        JSONObject mapTypes = JSON.parseObject(simpleObject);
        String areaid = mapTypes.getString("areaid");
        String typeid = mapTypes.getString("typeid");
        if (areaid == null || typeid == null) {
            return R.error();
        }
        EntityWrapper ew = new EntityWrapper();
        ew.setEntity(new ArticleEntity());
        if (StringUtils.isNotEmpty(areaid)) {
            ew.eq("areaid", areaid);
        }
        if (StringUtils.isNotEmpty(typeid)) {
            ew.eq("typeid", typeid);
        }
        ew.eq("isshow", 0).orderBy("sort desc,id desc");
        List<ArticleEntity> articleEntities = articleService.selectList(ew);
        for (int i = 0; i < articleEntities.size(); i++) {
            if (StringUtils.isNotEmpty(articleEntities.get(i).getTitleimg())) {
                String fileSavePath = "http://www.yanzuohotel.com/shenglian-fast/static/article/" + articleEntities.get(i).getTitleimg();
                articleEntities.get(i).setTitleimg(fileSavePath);
            }
        }
        return R.ok().put("articlelist", articleEntities);
    }

    /**
     * 商品信息列表
     *
     * @return
     */
    @RequestMapping("/goodslist")
    public R getgoodstype() {
        List<GoodtypeEntity> goodtypeEntities = goodtypeService.selectList(new EntityWrapper<GoodtypeEntity>().eq("isshow", 0).orderBy("sort desc,id desc"));
        for (int i = 0; i < goodtypeEntities.size(); i++) {
            String typeid = goodtypeEntities.get(i).getId().toString();
            EntityWrapper ew = new EntityWrapper();
            ew.setEntity(new GoodEntity());
            ew.eq("isshow", 0).orderBy("sort desc,id desc");
            if (StringUtils.isNotEmpty(typeid)) {
                ew.eq("typeid", typeid);
            }
            List<GoodEntity> goodEntities = goodService.selectList(ew);
            for (int j = 0; j < goodEntities.size(); j++) {
                if (StringUtils.isNotEmpty(goodEntities.get(j).getImgurl())) {
                    String fileSavePath = "http://www.yanzuohotel.com/shenglian-fast/static/goods/" + goodEntities.get(j).getImgurl();
                    goodEntities.get(j).setImgurl(fileSavePath);
                }
            }
            goodtypeEntities.get(i).setGoodEntities(goodEntities);
        }
        return R.ok().put("typelist", goodtypeEntities);
    }

    /**
     * 商品详细
     */
    @RequestMapping("/goodsinfo")
    private R getgoodsinfo(@RequestBody String simpleObject) {
        JSONObject mapTypes = JSON.parseObject(simpleObject);
        String goodid = mapTypes.getString("goodid");
        if (goodid == null) {
            return R.error();
        }
        GoodEntity goodEntity = goodService.selectById(goodid);
        return R.ok().put("goodinfo", goodEntity);
    }

    /**
     * 订单列表
     */
    @RequestMapping("/recepitlist")
    private R getrecepitlist(@RequestBody String simpleObject) {
        JSONObject mapTypes = JSON.parseObject(simpleObject);
        String userid = mapTypes.getString("userid");
        String status = mapTypes.getString("status");
        String page = mapTypes.getString("page");
        String pagesize = mapTypes.getString("pagesize");
        if (userid == null) {
            return R.error();
        }
        int currPage = Integer.parseInt(page);
        int limit = Integer.parseInt(pagesize);
        List<GoodreceiptEntity> goodreceiptEntities = goodreceiptService.selectList(new EntityWrapper<GoodreceiptEntity>()
                .eq("status", status)
                .eq("customerid", userid)
                .orderBy("id desc").last("limit " + (currPage - 1) * limit + "," + limit));
        return R.ok().put("nopaylist", goodreceiptEntities);
    }

    /**
     * 订单详细
     */
    @RequestMapping("/recepitinfo")
    private R getrecepitinfo(@RequestBody String simpleObject) {
        JSONObject mapTypes = JSON.parseObject(simpleObject);
        String recepitid = mapTypes.getString("receiptid");
        if (recepitid == null) {
            return R.error();
        }
        GoodreceiptEntity goodreceiptEntity = goodreceiptService.selectById(recepitid);
        List<GoodrecepititemEntity> goodrecepititemEntities = goodrecepititemService.selectList(new EntityWrapper<GoodrecepititemEntity>().eq("receiptid", recepitid));
        for (int i = 0; i < goodrecepititemEntities.size(); i++) {
            GoodEntity goodEntity = goodService.selectById(goodrecepititemEntities.get(i).getGoodid());
            if (StringUtils.isNotEmpty(goodEntity.getImgurl())) {
                String fileSavePath = "http://www.yanzuohotel.com/shenglian-fast/static/goods/" + goodEntity.getImgurl();
                goodEntity.setImgurl(fileSavePath);
            }
            goodrecepititemEntities.get(i).setGoodEntity(goodEntity);
        }
        HotelinfoEntity hotelinfoEntity = hotelinfoService.selectOne(new EntityWrapper<HotelinfoEntity>().eq("isdefault", 0));
        return R.ok().put("recepit", goodreceiptEntity).put("recepititem", goodrecepititemEntities).put("phone", hotelinfoEntity.getPhone());
    }

    private static boolean checkIP(String ip) {
        if (ip == null || ip.length() == 0 || "unkown".equalsIgnoreCase(ip)
                || ip.split(".").length != 4) {
            return false;
        }
        return true;
    }

    /**
     * 订单提交
     */
    @RequestMapping("/recepitsub")
    private R recepitsub(@RequestBody String simpleObject, HttpServletRequest request1) throws WxPayException, WeixinException {
        JSONObject mapTypes = JSON.parseObject(simpleObject);
        String userid = mapTypes.getString("userid");
        String username = mapTypes.getString("username");
        String receiptcode = mapTypes.getString("receiptcode");
        String roomcode = mapTypes.getString("roomcode");
        String phone = mapTypes.getString("phone");
        String people = mapTypes.getString("people");
        String remark = mapTypes.getString("remark");
        String sendtime = mapTypes.getString("sendtime");
        String totalmoney = mapTypes.getString("totalmoney");

        String ip = request1.getHeader("x-forwarded-for");
        if (!checkIP(ip)) {
            ip = request1.getHeader("Proxy-Client-IP");
        }
        if (!checkIP(ip)) {
            ip = request1.getHeader("WL-Proxy-Client-IP");
        }
        if (!checkIP(ip)) {
            ip = request1.getRemoteAddr();
        }

        if (userid == null) {
            return R.error();
        }

        GoodreceiptEntity goodreceiptEntity = new GoodreceiptEntity();
        goodreceiptEntity.setReceiptcode(receiptcode);
        goodreceiptEntity.setCustomername(username);
        goodreceiptEntity.setAddress(roomcode);
        goodreceiptEntity.setPhone(phone);
        goodreceiptEntity.setPeoplenum(people);
        goodreceiptEntity.setRemark(remark);
        goodreceiptEntity.setSendtime(sendtime);
        goodreceiptEntity.setStatus(1);
        goodreceiptEntity.setTotalmoney(BigDecimal.valueOf(Float.parseFloat(totalmoney)));
        goodreceiptEntity.setCustomerid(Integer.parseInt(userid));
        goodreceiptService.insert(goodreceiptEntity);
        JSONArray recepitinfo = JSON.parseArray(mapTypes.getString("recepitinfo"));
        for (int i = 0; i < recepitinfo.size(); i++) {
            JSONObject info = recepitinfo.getJSONObject(i);
            String goodid = info.getString("id");
            String goodname = info.getString("name");
            String num = info.getString("count");
            String price = info.getString("price");
            BigDecimal money = BigDecimal.valueOf(Integer.parseInt(num) * Float.parseFloat(price));
            GoodrecepititemEntity goodrecepititemEntity = new GoodrecepititemEntity();
            goodrecepititemEntity.setReceiptid(goodreceiptEntity.getId());
            goodrecepititemEntity.setGoodid(Integer.parseInt(goodid));
            goodrecepititemEntity.setGoodname(goodname);
            goodrecepititemEntity.setNum(Integer.parseInt(num));
            goodrecepititemEntity.setPrice(BigDecimal.valueOf(Float.parseFloat(price)));
            goodrecepititemEntity.setTotalmoney(money);
            goodrecepititemService.insert(goodrecepititemEntity);
        }

        //微信下单
/*        WxuserinfoEntity wxuserinfoEntity = wxuserinfoService.selectById(userid);
        WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
        request.setAppid(appId);  //公众号appId
        request.setOpenid(wxuserinfoEntity.getOpenid()); //用户openid
        request.setBody("晏坐民宿-订餐支付"); //商品描述
        request.setOutTradeNo(receiptcode);  //订单号
        request.setTotalFee(yuanToFen(totalmoney));  //总金额
        request.setSpbillCreateIp(ip);  //终端IP
        request.setNotifyUrl("http://www.yanzuohotel.com/shenglian-fast/app/weixinapp/payurl"); //通知地址
        request.setTradeType("JSAPI"); //交易类型
        WxPayUnifiedOrderResult result = this.wxService.unifiedOrder(request);

        Map<String, String> map = new HashMap<>();
        map.put("appId", appId); //公众号appId
        map.put("timeStamp", String.valueOf((System.currentTimeMillis() / 1000)));  //当前时间戳
        map.put("nonceStr", getRandomChar(32));  //随机字符串(32位)
        map.put("package", "prepay_id=" + result.getPrepayId());  //统一下单接口返回的prepay_id
        map.put("signType", "MD5");  //签名方式
        String paySign = getSign(map, paySerect);
        map.put("paySign", paySign);  //签名
        return R.ok().put("receiptid", goodreceiptEntity.getId()).put("result", map);*/

        //发送微信通知
        List<WxuserinfoEntity> wxuserinfoEntities = wxuserinfoService.selectList(
                new EntityWrapper<WxuserinfoEntity>().eq("isstaff", 1)
                        .eq("isdcnotice", 1).eq("subscribe", 1));
        Weixin weixin = new Weixin();
        for (int i = 0; i < wxuserinfoEntities.size(); i++) {
            if (StringUtils.isNotEmpty(wxuserinfoEntities.get(i).getOpenid())) {
                List<TemplateData> templateDataList = new ArrayList<>();
                TemplateData templateData = new TemplateData();
                templateData.setColor("red");
                templateData.setValue("您有一条新的点餐信息，请及时处理!");
                templateData.setKey("first");
                templateDataList.add(templateData);
                TemplateData templateData1 = new TemplateData();
                templateData1.setColor("");
                templateData1.setValue(goodreceiptEntity.getCustomername());
                templateData1.setKey("keyword1");
                templateDataList.add(templateData1);
                TemplateData templateData2 = new TemplateData();
                templateData2.setColor("");
                templateData2.setValue(goodreceiptEntity.getReceiptcode());
                templateData2.setKey("keyword2");
                templateDataList.add(templateData2);
                TemplateData templateData3 = new TemplateData();
                templateData3.setColor("");
                templateData3.setValue(goodreceiptEntity.getSendtime());
                templateData3.setKey("keyword3");
                templateDataList.add(templateData3);
                TemplateData templateData4 = new TemplateData();
                templateData4.setColor("");
                templateData4.setValue("点击查看订单详情");
                templateData4.setKey("remark");
                templateDataList.add(templateData4);
                weixin.message().sendTemplateMessage(wxuserinfoEntities.get(i).getOpenid(), "iXv3njyTfm4muwL2WeM1wgTOB47g-E9xzMGa1gj0-9o", templateDataList, "http://www.yanzuohotel.com/fillfeedback?id=" + goodreceiptEntity.getId() + "&wxuserinfoid=" + wxuserinfoEntities.get(i).getId());

                //保存通知信息
                GoodnoticeEntity goodnoticeEntity = goodnoticeService.selectOne(
                        new EntityWrapper<GoodnoticeEntity>().eq("customerid", goodreceiptEntity.getCustomerid())
                                .andNew("receiptid", goodreceiptEntity.getId()));
                if (goodnoticeEntity == null) {
                    GoodnoticeEntity goodnoticeEntity1 = new GoodnoticeEntity();
                    goodnoticeEntity1.setCustomerid(goodreceiptEntity.getCustomerid());
                    goodnoticeEntity1.setReceiptid(goodreceiptEntity.getId());
                    goodnoticeEntity1.setSendtime(new Date());
                    goodnoticeService.insert(goodnoticeEntity1);
                }
            }
        }

        return R.ok().put("receiptid", goodreceiptEntity.getId());
    }

    /**
     * 支付回调地址
     */
    @RequestMapping("/payurl")
    private Object NotifyUrl() {
        return null;
    }

    /**
     * 订单支付
     */
    @RequestMapping("/receiptpay")
    private R receiptpay(@RequestBody String simpleObject, HttpServletRequest request1) throws WxPayException {
        JSONObject mapTypes = JSON.parseObject(simpleObject);
        String receiptid = mapTypes.getString("receiptid");
        if (receiptid == null) {
            return R.error();
        }
        GoodreceiptEntity goodreceiptEntity = goodreceiptService.selectById(receiptid);
        if (goodreceiptEntity != null) {
            String ip = request1.getHeader("x-forwarded-for");
            if (!checkIP(ip)) {
                ip = request1.getHeader("Proxy-Client-IP");
            }
            if (!checkIP(ip)) {
                ip = request1.getHeader("WL-Proxy-Client-IP");
            }
            if (!checkIP(ip)) {
                ip = request1.getRemoteAddr();
            }
            //微信下单
            WxuserinfoEntity wxuserinfoEntity = wxuserinfoService.selectById(goodreceiptEntity.getCustomerid());
            WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
            request.setAppid(appId);  //公众号appId
            request.setOpenid(wxuserinfoEntity.getOpenid()); //用户openid
            request.setBody("晏坐民宿-订餐支付"); //商品描述
            request.setOutTradeNo(goodreceiptEntity.getReceiptcode() + getRandomChar(4));  //订单号
            request.setTotalFee(yuanToFen(goodreceiptEntity.getTotalmoney().toString()));  //总金额
            request.setSpbillCreateIp(ip);  //终端IP
            request.setNotifyUrl("http://www.yanzuohotel.com/shenglian-fast/app/weixinapp/payurl"); //通知地址
            request.setTradeType("JSAPI"); //交易类型
            WxPayUnifiedOrderResult result = this.wxService.unifiedOrder(request);

            Map<String, String> map = new HashMap<>();
            map.put("appId", appId); //公众号id
            map.put("timeStamp", String.valueOf((System.currentTimeMillis() / 1000)));  //当前时间戳
            map.put("nonceStr", getRandomChar(32));  //随机字符串(32位)
            map.put("package", "prepay_id=" + result.getPrepayId());  //统一下单接口返回的prepay_id
            map.put("signType", "MD5");  //签名方式
            String paySign = getSign(map, paySerect);
            map.put("paySign", paySign);  //签名
            return R.ok().put("receiptid", goodreceiptEntity.getId()).put("result", map);
        } else {
            return R.error();
        }
    }

    /**
     * 支付完成
     */
    @RequestMapping("/paysuccess")
    private R paysuccess(@RequestBody String simpleObject) throws WeixinException {
        JSONObject mapTypes = JSON.parseObject(simpleObject);
        String receiptid = mapTypes.getString("receiptid");
        if (receiptid == null) {
            return R.error();
        }
        GoodreceiptEntity goodreceiptEntity = goodreceiptService.selectById(receiptid);
        goodreceiptEntity.setStatus(1);
        goodreceiptEntity.setChargetime(new Date());
        goodreceiptService.updateById(goodreceiptEntity);

        //发送微信通知
        List<WxuserinfoEntity> wxuserinfoEntities = wxuserinfoService.selectList(
                new EntityWrapper<WxuserinfoEntity>().eq("isstaff", 1)
                        .eq("isdcnotice", 1).eq("subscribe", 1));
        Weixin weixin = new Weixin();
        for (int i = 0; i < wxuserinfoEntities.size(); i++) {
            if (StringUtils.isNotEmpty(wxuserinfoEntities.get(i).getOpenid())) {
                List<TemplateData> templateDataList = new ArrayList<>();
                TemplateData templateData = new TemplateData();
                templateData.setColor("red");
                templateData.setValue("您有一条新的点餐信息，请及时处理!");
                templateData.setKey("first");
                templateDataList.add(templateData);
                TemplateData templateData1 = new TemplateData();
                templateData1.setColor("");
                templateData1.setValue(goodreceiptEntity.getCustomername());
                templateData1.setKey("keyword1");
                templateDataList.add(templateData1);
                TemplateData templateData2 = new TemplateData();
                templateData2.setColor("");
                templateData2.setValue(goodreceiptEntity.getReceiptcode());
                templateData2.setKey("keyword2");
                templateDataList.add(templateData2);
                TemplateData templateData3 = new TemplateData();
                templateData3.setColor("");
                templateData3.setValue(goodreceiptEntity.getSendtime());
                templateData3.setKey("keyword3");
                templateDataList.add(templateData3);
                TemplateData templateData4 = new TemplateData();
                templateData4.setColor("");
                templateData4.setValue("点击查看订单详情");
                templateData4.setKey("remark");
                templateDataList.add(templateData4);
                weixin.message().sendTemplateMessage(wxuserinfoEntities.get(i).getOpenid(), "iXv3njyTfm4muwL2WeM1wgTOB47g-E9xzMGa1gj0-9o", templateDataList, "http://www.yanzuohotel.com/fillfeedback?id=" + goodreceiptEntity.getId() + "&wxuserinfoid=" + wxuserinfoEntities.get(i).getId());

                //保存通知信息
                GoodnoticeEntity goodnoticeEntity = goodnoticeService.selectOne(
                        new EntityWrapper<GoodnoticeEntity>().eq("customerid", goodreceiptEntity.getCustomerid())
                                .andNew("receiptid", goodreceiptEntity.getId()));
                if (goodnoticeEntity == null) {
                    GoodnoticeEntity goodnoticeEntity1 = new GoodnoticeEntity();
                    goodnoticeEntity1.setCustomerid(goodreceiptEntity.getCustomerid());
                    goodnoticeEntity1.setReceiptid(goodreceiptEntity.getId());
                    goodnoticeEntity1.setSendtime(new Date());
                    goodnoticeService.insert(goodnoticeEntity1);
                }
            }
        }
        return R.ok();
    }

    /**
     * 订餐通知信息
     */
    @RequestMapping("/goodreceiptinfo")
    public R goodreceiptinfo(@RequestBody String simpleObject) {
        JSONObject mapTypes = JSON.parseObject(simpleObject);
        String id = mapTypes.getString("id");
        if (id == null) {
            return R.error();
        }
        GoodnoticeEntity goodnoticeEntity = goodnoticeService.selectOne(new EntityWrapper<GoodnoticeEntity>().eq("receiptid", id));
        GoodreceiptEntity goodreceiptEntity = goodreceiptService.selectById(id);
        List<GoodrecepititemEntity> goodrecepititemEntities = goodrecepititemService.selectList(new EntityWrapper<GoodrecepititemEntity>().eq("receiptid", goodreceiptEntity.getId()));
        for (int i = 0; i < goodrecepititemEntities.size(); i++) {
            GoodEntity goodEntity = goodService.selectById(goodrecepititemEntities.get(i).getGoodid());
            if (StringUtils.isNotEmpty(goodEntity.getImgurl())) {
                String fileSavePath = "http://www.yanzuohotel.com/shenglian-fast/static/goods/" + goodEntity.getImgurl();
                goodEntity.setImgurl(fileSavePath);
            }
            goodrecepititemEntities.get(i).setGoodEntity(goodEntity);
        }
        return R.ok().put("recepit", goodreceiptEntity).put("recepititem", goodrecepititemEntities).put("notice", goodnoticeEntity);
    }

    /**
     * 订餐回复
     */
    @RequestMapping("/receiptreply")
    private R receiptreply(@RequestBody String simpleObject) throws WeixinException {
        JSONObject mapTypes = JSON.parseObject(simpleObject);
        String id = mapTypes.getString("id");
        String contents = mapTypes.getString("contents");
        String wxuserinfoid = mapTypes.getString("wxuserinfoid");

        if (id == null || wxuserinfoid == null) {
            return R.error();
        }

        GoodnoticeEntity goodnoticeEntity = goodnoticeService.selectOne(new EntityWrapper<GoodnoticeEntity>().eq("receiptid", id));
        goodnoticeEntity.setIsreply(1);
        goodnoticeEntity.setRecontent(contents);
        goodnoticeEntity.setReuser(wxuserinfoid);
        goodnoticeEntity.setRetime(new Date());
        goodnoticeService.updateById(goodnoticeEntity);

        GoodreceiptEntity goodreceiptEntity = goodreceiptService.selectById(id);

        //微信发送给用户
        WxuserinfoEntity wxuserinfoEntity = wxuserinfoService.selectById(goodnoticeEntity.getCustomerid());
        Weixin weixin = new Weixin();
        if (StringUtils.isNotEmpty(wxuserinfoEntity.getOpenid())) {
            List<TemplateData> templateDataList = new ArrayList<>();
            TemplateData templateData = new TemplateData();
            templateData.setColor("red");
            templateData.setValue("商家回复：" + contents);
            templateData.setKey("first");
            templateDataList.add(templateData);
            TemplateData templateData1 = new TemplateData();
            templateData1.setColor("");
            templateData1.setValue(goodreceiptEntity.getCustomername());
            templateData1.setKey("keyword1");
            templateDataList.add(templateData1);
            TemplateData templateData2 = new TemplateData();
            templateData2.setColor("");
            templateData2.setValue(goodreceiptEntity.getReceiptcode());
            templateData2.setKey("keyword2");
            templateDataList.add(templateData2);
            TemplateData templateData3 = new TemplateData();
            templateData3.setColor("");
            templateData3.setValue(goodreceiptEntity.getSendtime());
            templateData3.setKey("keyword3");
            templateDataList.add(templateData3);
            TemplateData templateData4 = new TemplateData();
            templateData4.setColor("");
            templateData4.setValue("点击查看订单详情");
            templateData4.setKey("remark");
            templateDataList.add(templateData4);
            weixin.message().sendTemplateMessage(wxuserinfoEntity.getOpenid(), "iXv3njyTfm4muwL2WeM1wgTOB47g-E9xzMGa1gj0-9o", templateDataList, "http://www.yanzuohotel.com/fillfeedback?id=" + goodnoticeEntity.getReceiptid() + "&wxuserinfoid=" + wxuserinfoEntity.getId());
        }
        return R.ok();
    }


    /**
     * 订房通知信息
     */
    @RequestMapping("/roomreceiptinfo")
    private R roomreceiptinfo(@RequestBody String simpleObject) {
        JSONObject mapTypes = JSON.parseObject(simpleObject);
        String id = mapTypes.getString("id");
        if (id == null) {
            return R.error();
        }
        RoomreceiptEntity roomreceiptEntity = roomreceiptService.selectById(id);
        RoomtypeEntity roomtypeEntity = roomtypeService.selectById(roomreceiptEntity.getRoomtype());
        roomreceiptEntity.setTypename(roomtypeEntity.getTypename());
        return R.ok().put("receipt", roomreceiptEntity);
    }

    /**
     * 客户房间绑定
     */
    @RequestMapping("/bindroom")
    private R bindroom(@RequestBody String simpleObject) {
        JSONObject mapTypes = JSON.parseObject(simpleObject);
        String key = mapTypes.getString("key");
        String userid = mapTypes.getString("userid");
        if (userid == null) {
            return R.error();
        }
        RoominfoEntity roominfoEntity = roominfoService.selectOne(new EntityWrapper<RoominfoEntity>().eq("secretkey", key));
        if (roominfoEntity != null) {
            RoomuserEntity roomuserEntity = roomuserService.selectOne(new EntityWrapper<RoomuserEntity>().eq("userid", userid)
                    .eq("roomid", roominfoEntity.getId()));
            if (roomuserEntity != null) {
                roomuserEntity.setStatus(1);
                roomuserEntity.setCreatetime(new Date());
                roomuserEntity.setSettlenum(roomuserEntity.getSettlenum() + 1);
                roomuserService.updateById(roomuserEntity);
            } else {
                RoomuserEntity roomuserEntity1 = new RoomuserEntity();
                roomuserEntity1.setRoomid(roominfoEntity.getId());
                roomuserEntity1.setUserid(Integer.parseInt(userid));
                roomuserEntity1.setStatus(1);
                roomuserEntity1.setCreatetime(new Date());
                roomuserEntity1.setSettlenum(1);
                roomuserService.insert(roomuserEntity1);
            }
            return R.ok().put("roominfo", roominfoEntity);
        } else {
            return R.error();
        }
    }

    /**
     * 客户房间解綁
     */
    @RequestMapping("/rebindroom")
    private R rebindroom(@RequestBody String simpleObject) {
        JSONObject mapTypes = JSON.parseObject(simpleObject);
        String roomid = mapTypes.getString("roomid");
        String userid = mapTypes.getString("userid");
        if (userid == null || roomid == null) {
            return R.error();
        }
        RoomuserEntity roomuserEntity = roomuserService.selectOne(new EntityWrapper<RoomuserEntity>().eq("userid", userid)
                .eq("roomid", roomid));
        if (roomuserEntity != null) {
            roomuserEntity.setStatus(0);
            roomuserEntity.setSettlenum(roomuserEntity.getSettlenum() - 1);
            roomuserService.updateById(roomuserEntity);
            return R.ok();
        } else {
            return R.error();
        }
    }

    /**
     * 客户房间信息
     */
    @RequestMapping("/getroomuser")
    private R getroomuser(@RequestBody String simpleObject) {
        JSONObject mapTypes = JSON.parseObject(simpleObject);
        String userid = mapTypes.getString("userid");
        if (userid == null) {
            return R.error();
        }
        RoomuserEntity roomuserEntity = roomuserService.selectOne(new EntityWrapper<RoomuserEntity>().eq("userid", userid).eq("status", 1));
        if (roomuserEntity != null) {
            RoominfoEntity roominfoEntity = roominfoService.selectById(roomuserEntity.getRoomid());
            WxuserinfoEntity wxuserinfoEntity = wxuserinfoService.selectById(roomuserEntity.getUserid());
            return R.ok().put("userinfo", wxuserinfoEntity).put("roominfo", roominfoEntity);
        } else {
            return R.error();
        }
    }

    /**
     * 投诉建议
     */
    @RequestMapping("/feedback")
    private R feedback(@RequestBody String simpleObject) throws WeixinException {
        JSONObject mapTypes = JSON.parseObject(simpleObject);
        String itype = mapTypes.getString("itype");
        String userid = mapTypes.getString("userid");
        String praise = mapTypes.getString("praise");
        String contents = mapTypes.getString("contents");
        String imgurl = mapTypes.getString("imgurl");

        if (userid == null) {
            return R.error();
        }

        FeedbackEntity feedbackEntity = new FeedbackEntity();
        feedbackEntity.setItype(Integer.parseInt(itype));
        feedbackEntity.setCustomerid(Integer.parseInt(userid));
        feedbackEntity.setPraise(praise);
        feedbackEntity.setContents(contents);
        feedbackEntity.setImgurl(imgurl);
        feedbackEntity.setSendtime(new Date());
        feedbackService.insert(feedbackEntity);

        //发送微信通知
        List<WxuserinfoEntity> wxuserinfoEntities = wxuserinfoService.selectList(
                new EntityWrapper<WxuserinfoEntity>().eq("isstaff", 1)
                        .eq("isdpnotice", 1).eq("subscribe", 1));
        Weixin weixin = new Weixin();
        WxuserinfoEntity wxuserinfoEntity = wxuserinfoService.selectById(userid);
        for (int i = 0; i < wxuserinfoEntities.size(); i++) {
            if (StringUtils.isNotEmpty(wxuserinfoEntities.get(i).getOpenid())) {
                List<TemplateData> templateDataList = new ArrayList<>();
                TemplateData templateData = new TemplateData();
                templateData.setColor("red");
                templateData.setValue("有新的意见反馈信息!");
                templateData.setKey("first");
                templateDataList.add(templateData);
                TemplateData templateData1 = new TemplateData();
                templateData1.setColor("");
                templateData1.setValue(wxuserinfoEntity.getNickname());
                templateData1.setKey("keyword1");
                templateDataList.add(templateData1);
                TemplateData templateData2 = new TemplateData();
                templateData2.setColor("");
                templateData2.setValue(contents);
                templateData2.setKey("keyword2");
                templateDataList.add(templateData2);
                TemplateData templateData3 = new TemplateData();
                templateData3.setColor("");
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
                String audittime = df.format(new Date());
                templateData3.setValue(audittime);
                templateData3.setKey("keyword3");
                templateDataList.add(templateData3);
                TemplateData templateData4 = new TemplateData();
                templateData4.setColor("");
                templateData4.setValue("点击查看详情");
                templateData4.setKey("remark");
                templateDataList.add(templateData4);
                weixin.message().sendTemplateMessage(wxuserinfoEntities.get(i).getOpenid(), "lPE0-885aInE0_MVKR2qgV6TrMqjX7EhLCVexauJE3s", templateDataList, "http://www.yanzuohotel.com/dpfeedback?id=" + feedbackEntity.getId() + "&wxuserinfoid=" + wxuserinfoEntities.get(i).getId());
            }
        }
        return R.ok();
    }

    /**
     * 投诉建议图片上传
     */
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        String pictureName = UUID.randomUUID().toString() + ".jpg";
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        String fileSavePath = path + "/static/feedback/";
        File f = new File(fileSavePath);
        // 判断路径是否存在，不存在则创建
        if (!f.exists()) {
            f.mkdirs();
        }
        ImageHelper.compress(file.getInputStream(), new File(fileSavePath + pictureName), 670);
        return R.ok().put("name", pictureName);
    }

    /**
     * 删除建议图片
     */
    @PostMapping("/picdelete")
    private R picdelete(@RequestBody String simpleObject) {
        JSONObject mapTypes = JSON.parseObject(simpleObject);
        String name = mapTypes.getString("name");
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        String fileSavePath = path + "/static/feedback/" + name;
        //删除文件夹中的图片文件
        File file = new File(fileSavePath);//文件路径
        file.delete();
        return R.ok();
    }

    /**
     * 建议信息详细
     */
    @PostMapping("/feedinfo")
    private R feedinfo(@RequestBody String simpleObject) {
        JSONObject mapTypes = JSON.parseObject(simpleObject);
        String id = mapTypes.getString("id");
        if (id == null) {
            return R.error();
        }
        Map<String, Object> map = feedbackService.getinfo(Integer.parseInt(id));
        String img = map.get("imgurl").toString();
        String newlist = "";
        if (StringUtils.isNotEmpty(img)) {
            String[] imglist = img.split(",");
            for (int j = 0; j < imglist.length; j++) {
                String fileSavePath = "http://www.yanzuohotel.com/shenglian-fast/static/feedback/" + imglist[j];
                newlist += fileSavePath + ",";
            }
        }
        if (org.apache.commons.lang.StringUtils.isNotEmpty(newlist)) {
            newlist = newlist.substring(0, newlist.length() - 1);
        }
        map.put("imgurl", newlist);
        return R.ok().put("feedinfo", map);
    }

    /**
     * 建议回复
     */
    @PostMapping("/replyfeed")
    private R replyfeed(@RequestBody String simpleObject) throws WeixinException {
        JSONObject mapTypes = JSON.parseObject(simpleObject);
        String id = mapTypes.getString("id");
        String contents = mapTypes.getString("contents");
        String wxuserinfoid = mapTypes.getString("wxuserinfoid");

        if (id == null || wxuserinfoid == null) {
            return R.error();
        }

        FeedbackEntity feedbackEntity = feedbackService.selectById(id);
        feedbackEntity.setStatus(1);
        feedbackEntity.setReplycontent(contents);
        feedbackEntity.setReplystaff(wxuserinfoid);
        feedbackEntity.setReplytime(new Date());
        feedbackService.updateById(feedbackEntity);

        //微信发送给用户
        WxuserinfoEntity wxuserinfoEntity = wxuserinfoService.selectById(feedbackEntity.getCustomerid());
        Weixin weixin = new Weixin();
        if (StringUtils.isNotEmpty(wxuserinfoEntity.getOpenid())) {
            List<TemplateData> templateDataList = new ArrayList<>();
            TemplateData templateData = new TemplateData();
            templateData.setColor("red");
            templateData.setValue("商家回复：" + contents);
            templateData.setKey("first");
            templateDataList.add(templateData);
            TemplateData templateData1 = new TemplateData();
            templateData1.setColor("");
            templateData1.setValue(wxuserinfoEntity.getNickname());
            templateData1.setKey("keyword1");
            templateDataList.add(templateData1);
            TemplateData templateData2 = new TemplateData();
            templateData2.setColor("");
            templateData2.setValue(feedbackEntity.getContents());
            templateData2.setKey("keyword2");
            templateDataList.add(templateData2);
            TemplateData templateData3 = new TemplateData();
            templateData3.setColor("");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            String audittime = df.format(new Date());
            templateData3.setValue(audittime);
            templateData3.setKey("keyword3");
            templateDataList.add(templateData3);
            TemplateData templateData4 = new TemplateData();
            templateData4.setColor("");
            templateData4.setValue("感谢您反馈，我们会慎重考虑您的建议。祝您生活愉快!");
            templateData4.setKey("remark");
            templateDataList.add(templateData4);
            weixin.message().sendTemplateMessage(wxuserinfoEntity.getOpenid(), "lPE0-885aInE0_MVKR2qgV6TrMqjX7EhLCVexauJE3s", templateDataList, "http://www.yanzuohotel.com/dpfeedback?id=" + feedbackEntity.getId() + "&wxuserinfoid=" + wxuserinfoEntity.getId());
        }
        return R.ok();
    }

    /**
     * 早餐信息
     */
    @RequestMapping("/breakfast")
    private R breakfast() {
        List<BreakfastEntity> breakfastEntities = breakfastService.selectList(new EntityWrapper<BreakfastEntity>().eq("isshow", 0).orderBy("sort desc,id desc"));
        for (int i = 0; i < breakfastEntities.size(); i++) {
            if (StringUtils.isNotEmpty(breakfastEntities.get(i).getImgurl())) {
                String fileSavePath = "http://www.yanzuohotel.com/shenglian-fast/static/breakfast/" + breakfastEntities.get(i).getImgurl();
                breakfastEntities.get(i).setImgurl(fileSavePath);
            }
        }
        return R.ok().put("list", breakfastEntities);
    }
}
